package cn.base.web.support.id;

import cn.hutool.core.net.NetUtil;
import cn.rengy.tool.core.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.sql.Timestamp;

@Component
@Slf4j
public class InitSnowflake {
    @Autowired
    private SysWorkerNodeService sysWorkerNodeService;
    private int startNumber;

    private int workerId;

    @EventListener(ApplicationReadyEvent.class)
    public void handleApplicationReadyEvent(ApplicationReadyEvent event) {
        init();
    }

    private void init(){
        log.info("初始化_Snowflake");
        String ip= NetUtil.getLocalhostStr();
        String hostname=NetUtil.getLocalHostName();
        //nodeid+1
        SysWorkerNodePO workerNode=sysWorkerNodeService.getWorker(hostname,ip);
        startNumber=workerNode.getRestartNumber();
        workerId=workerNode.getWorkerId();
        IdGenerator.init(startNumber,workerId);
        //
    }

    @PreDestroy
    private void destroy(){
        //startNumber与当前数据库一致，nodeid-1
        log.info("IdGenerator PreDestroy");
        sysWorkerNodeService.stop(workerId, startNumber);
    }

    /**
     * 每天凌晨0点0分执行
     * 同步雪花时钟
     */
    @Scheduled(cron="0 0 0 * * ?")
    private void syncTime(){
        log.info("同步前系统时间:{},雪花时钟时间:{}",
                new Timestamp(System.currentTimeMillis()).toString(),
                IdGenerator.getSnowflake().getSnowflakeClockTime()
        );
        IdGenerator.getSnowflake().syncSnowflakeClockTime();
        log.info("同步后系统时间:{},雪花时钟时间:{}",
                new Timestamp(System.currentTimeMillis()).toString(),
                IdGenerator.getSnowflake().getSnowflakeClockTime()
        );
    }
}
